<template>
  <div class="home">
    <header>
      <div>
        <img src="../assets/logo.svg" class="logo" />
      </div>
      <div class="login">
        <span>{{successName}}</span>
        <el-button type="primary" plain @click="dialogFormVisible = true">登录</el-button>
        <el-button type="primary" plain @click="handleLogout">退出</el-button>
        <i class="el-icon-shopping-cart-full" @click="handleCart"></i>
      </div>
      <el-dialog title="登陆界面" :visible.sync="dialogFormVisible">
        <el-form :model="form" status-icon :rules="rules">
          <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pass" :label-width="formLabelWidth">
            <el-input type="password" v-model="form.pass"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleLogin">确 定</el-button>
        </div>
      </el-dialog>
    </header>
    <div class="nav">
      <span style="font-weight:800">首页</span>
      <span>></span>
      <span>商品详情</span>
    </div>
    <div class="priceNav">
      <div class="pright">
        <span>排序:</span>
        <span class="sort" :class="sort=='default'?'active':''" @click="handleDefault">默认</span>
        <span
          class="sort"
          :class="sort=='default'?'':'active'"
          @click="handleSort"
        >价格 {{asc?'↑':'↓'}}</span>
      </div>
    </div>
    <section>
      <div class="price">
        <h3>PRICE:</h3>
        <div v-for="item of searchPrice" :key="item.id">
          <p @click="handlePrice(item.gt,item.lt)" class="prices">{{item.gt}}-{{item.lt}}</p>
        </div>
      </div>

      <div class="content">
        <div class="container">
          <div
            v-for="item of goodsList.slice(8*currentPage-8,8*currentPage)"
            :key="item.productName"
            class="item"
          >
            <img :src="item.productImage" class="product" />
            <p class="name">{{item.productName}}</p>
            <p class="money">￥ {{item.salePrice}}</p>
            <p class="buy">
              <el-button
                type="danger"
                plain
                style="width:100%"
                @click="addCart(item.productId)"
              >加入购物车</el-button>
            </p>
          </div>
        </div>

        <!-- page-size默认为10，表示一页展示的条数，total填入数组总长度 -->
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="pagesize"
          :total="goodsList.length"
          :current-page="currentPage"
          @current-change="handlecurrent"
        ></el-pagination>
      </div>
    </section>
  </div>
</template>

<script>
// @ is an alias to /src

export default {
  name: "home",
  mounted() {
    this.getList();
    this.$http.get('/users/checkLogin').then(res=>{
      if(res.data.code==200){
        this.successName = res.data.result;
        this.isLogin = true;
      }else{
        this.isLogin = false;
      }
     })
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      }
    };
    return {
      goodsList: [],
      pagesize: 8,
      currentPage: 1, //起始页
      searchPrice: [
        { gt: 0, lt: 100, id: 1001 },
        { gt: 100, lt: 500, id: 1002 },
        { gt: 500, lt: 1000, id: 1003 },
        { gt: 1000, lt: 5000, id: 1004 }
      ],
      sort: "default",
      asc: true,
      dialogFormVisible: false,
      form: {
        username: "",
        pass: ""
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur", required: true }],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ]
      },
      formLabelWidth: "120px",
      successName:"",
      isLogin:false
    };
  },
  methods: {
    addCart(id) {
      if(this.isLogin){
      this.$http({
        method: "post",
        url: "/users/addCart",
        data: {
          productId: id
        }
      }).then(res => {
        console.log(res.data);
        if (res.data.code === 200) {
          this.$message({
            message: "添加成功",
            type: "success"
          });
        } else {
          this.$message({
            message: "已经添加到购物车",
            type: "warning"
          });
        }
      });
      }else{
        this.$message({
          type:'warning',
          message:'请您先登录'
        })
      }

    },
    getList() {
      this.$http("goods/list").then(res => {
        this.goodsList = res.data.result;
      });
    },
    handlePrice(gt, lt) {
      this.$http(`goods/price?gt=${gt}&lt=${lt}`).then(res => {
        console.log(res);
        this.goodsList = res.data.result;
      });
    },
    handlecurrent(value) {
      this.currentPage = value;
      console.log(this.currentPage);
    },
    handleSort() {
      this.sort = "sort";
      this.asc = !this.asc;
      if (this.asc) {
        this.goodsList.sort((a, b) => a["salePrice"] - b["salePrice"]);
      } else {
        this.goodsList.sort((a, b) => b["salePrice"] - a["salePrice"]);
      }
    },
    handleDefault() {
      this.sort = "default";
      this.getList();
    },
    handleLogin(){
      if(this.form.username && this.form.pass){
        this.$http({
          url:'/users/login',
          method:'post',
          data:{
            userName:this.form.username,
            userPwd:this.form.pass
          }
        }).then(res=>{
          if(res.data.code===200){
            this.$message({
              duration:1000,
              message:res.data.msg,
              type:'success'
            });
            this.successName = res.data.userName;
            this.dialogFormVisible = false;
            this.isLogin = true;
          }else{
            this.$message({
              duration:1000,
              message:res.data.msg,
              type:'error'
            })
          }
        })
      }else{
        this.$message({
          message:'用户名和密码不能为空',
          duration:1000,
          type:'error'
        })
      }
    },
    handleLogout(){
      this.$http({
        url:'/users/logout',
        method:'post'
      }).then(res=>{
        console.log(res);
        this.$message({
          message:res.data.msg,
          duration:1000
        });
        this.successName = "";
        this.isLogin =false;
      })
    },
    handleCart(){
      if(this.isLogin){
        this.$router.push(`/cart?userName=${this.successName}`)
      }else{
        this.$message({
          message:"请您先登录",
          type:'warning',
          duration:1000
        })
      }
    },
    checkLogin(){
    this.$http.get('/users/checkLogin').then(res=>{
      if(res.data.code==200){
        this.successName = res.data.result;
        return true;
      }else{
        return false;
      }
     })
    }
  },
  // beforeRouteLeave (to, from, next) {
  //   //只有执行next(),才会执行路由跳转
  //   console.log(1);
  // }
};
</script>
<style lang="less">
.home {
  background: #f5f7fc;
}
header {
  background: #fff;
  padding: 0 100px;
  display: flex;
  justify-content: space-between;
  .logo {
    height: 90px;
  }
  .login {
    line-height: 90px;
    font-size: 25px;
    i {
      margin-top: auto;
      margin-bottom: auto;
      padding-left: 10px;
    }
  }
}
.nav {
  padding: 30px 100px;
}
.priceNav {
  margin-left: 100px;
  margin-right: 100px;
  background: #fff;
  overflow: hidden;
  .pright {
    float: right;
    font-size: 15px;
    line-height: 50px;
    .sort {
      padding-left: 15px;
      padding-right: 10px;
      cursor: pointer;
    }
  }
}
.item {
  width: 190px;
  background: #fff;
  margin-bottom: 20px;
  border: 1px solid #ededed;
  height: 378px;
}
.product {
  width: 190px;
}
.content {
  float: left;
  width: 829px;
  .container {
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    min-height: 790px;
  }
}
section {
  padding: 0 100px;
  margin-top: 40px;
  // height: 1180px;
  overflow: hidden;
  min-width: 1149px;
}
.price {
  color: #776f65;
  width: 320px;
  text-align: center;
  float: left;
  .prices {
    margin-top: 30px;
  }
}
.name {
  text-align: center;
  font-weight: bolder;
  padding: 30px 0;
  color: #455460;
}
.money,
.buy {
  padding: 10px;
  color: #e07a72;
}
.active {
  color: #e07a72;
}
</style>
